﻿# 获取所有状态为失败的作业
$failedJobs = Get-Job | Where-Object { $_.State -eq 'Failed' }

# 检查是否有失败的作业
if (-not $failedJobs) {
    Write-Host "没有找到失败的作业。所有作业均成功完成或处于其他状态。" -ForegroundColor Green
    exit 0
}

# 显示失败作业的基本信息
Write-Host "发现 $($failedJobs.Count) 个失败作业:`n" -ForegroundColor Red
$failedJobs | Format-Table Id, Name, State, Location -AutoSize

# 逐个检查失败作业的详细信息
foreach ($job in $failedJobs) {
    Write-Host "`n=== 作业 ID: $($job.Id), 名称: $($job.Name) ===" -ForegroundColor Yellow
    
    # 尝试从作业的Error流中获取错误信息:cite[5]
    if ($job.Error) {
        Write-Host "错误信息 (来自 Error 流):" -ForegroundColor Red
        $job.Error | ForEach-Object { 
            Write-Host "    $($_.Exception.Message)" -ForegroundColor Red 
        }
    }
    
    # 尝试通过 Receive-Job 获取输出，这可能包含错误信息:cite[6]
    $jobOutput = Receive-Job -Job $job -ErrorAction SilentlyContinue -ErrorVariable receiveErrors
    if ($receiveErrors) {
        Write-Host "通过 Receive-Job 获取到的错误:" -ForegroundColor Red
        $receiveErrors | ForEach-Object { 
            Write-Host "    $($_.Exception.Message)" -ForegroundColor Red 
        }
    }
    
    # 检查子作业的详细错误信息（如果存在）:cite[6]
    if ($job.ChildJobs) {
        Write-Host "子作业详细错误:" -ForegroundColor Red
        foreach ($childJob in $job.ChildJobs) {
            # 显示子作业的状态信息:cite[5]
            if ($childJob.JobStateInfo.Reason) {
                Write-Host "    子作业 ID $($childJob.Id): $($childJob.JobStateInfo.Reason.Message)" -ForegroundColor Red
            }
            # 显示子作业的错误流:cite[5]
            if ($childJob.Error) {
                $childJob.Error | ForEach-Object { 
                    Write-Host "    子作业 ID $($childJob.Id) 错误: $($_.Exception.Message)" -ForegroundColor Red 
                }
            }
        }
    }
    
    Write-Host "----------------------------------------" -ForegroundColor Gray
}

# 提供清理失败作业的选项
Write-Host "`n是否要清理所有失败的作业? (y/N)" -ForegroundColor Cyan -NoNewline
$response = Read-Host
if ($response -eq 'y' -or $response -eq 'Y') {
    $failedJobs | Remove-Job
    Write-Host "已清理所有失败的作业。" -ForegroundColor Green
} else {
    Write-Host "保留失败的作业。你可以使用 Receive-Job -Id <作业ID> 查看详细信息。" -ForegroundColor Yellow
}